<?php

namespace app\api\controller;

use Qiniu\Auth;
use think\facade\Db;
use think\Response;
use think\facade\Request;
use think\facade\Config;
use app\common\controller\Frontend;
use app\api\model\Audio as AudioModel;
use app\api\model\Folder as FolderModel;
use app\common\library\AudioHelper;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;

class Audio extends Frontend
{
    protected array $noNeedLogin = ['realDeleteAudios', 'realDeleteSingleAudio', 'batchDeleteAudios', 'refreshFolderStats', 'testQiniuConnection', 'getFolders', 'getAllFolders', 'getAudios', 'getAvailableAudios', 'uploadAudio', 'uploadAudioWithInfo', 'createFolder', 'updateFolder', 'deleteFolder', 'moveAudio', 'renameAudio', 'deleteAudio', 'getUploadToken'];

    // 获取七牛云配置
    private function getQiniuConfig()
    {
        return Config::get('qiniu');
    }

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 获取上传凭证
     */
    public function getUploadToken(): Response
    {
        try {
            $config = $this->getQiniuConfig();
            $auth = new Auth($config['access_key'], $config['secret_key']);
            
            // 设置上传策略
            $policy = [
                'returnBody' => $config['upload_policy']['return_body']
            ];
            
            $token = $auth->uploadToken($config['bucket'], null, $config['upload_policy']['expires'], $policy);
            
            return $this->success('获取上传凭证成功', [
                'token' => $token,
                'domain' => $config['domain'],
                'supported_formats' => $config['supported_formats'],
                'max_file_size' => $config['max_file_size']
            ]);
        } catch (Exception $e) {
            return $this->error('获取上传凭证失败: ' . $e->getMessage());
        }
    }

    /**
     * 上传音频文件
     */
    public function uploadAudio(): Response
    {
        $roomId = $this->request->post('room_id', 0);
        $folderId = $this->request->post('folder_id', null);
        $files = $this->request->file('files');
        
        if (empty($roomId)) {
            return $this->error('房间ID不能为空');
        }

        if (empty($files)) {
            return $this->error('请选择要上传的音频文件');
        }

        // 如果不是数组，转换为数组
        if (!is_array($files)) {
            $files = [$files];
        }

        try {
            $config = $this->getQiniuConfig();
            $uploadedFiles = [];
            $auth = new Auth($config['access_key'], $config['secret_key']);
            $uploadMgr = new UploadManager();

            foreach ($files as $file) {
                // 验证文件类型
                $extension = strtolower($file->getOriginalExtension());
                if (!in_array($extension, $config['supported_formats'])) {
                    continue; // 跳过不支持的格式
                }

                // 验证文件大小
                if ($file->getSize() > $config['max_file_size']) {
                    continue; // 跳过超过大小限制的文件
                }

                // 生成文件名
                $fileName = 'audio/room' . $roomId . '/' . date('Ymd') . '/' . uniqid() . '.' . $extension;
                
                // 获取上传凭证
                $token = $auth->uploadToken($config['bucket']);
                
                // 上传到七牛云
                list($ret, $err) = $uploadMgr->putFile($token, $fileName, $file->getPathname());
                
                if ($err !== null) {
                    throw new \Exception('文件上传失败: ' . $err->message());
                }

                // 获取音频文件信息
                $originalName = $file->getOriginalName();
                $displayName = pathinfo($originalName, PATHINFO_FILENAME);
                $fileSize = $file->getSize();
                
                // 获取音频时长
                $duration = 0;
                try {
                    // 使用上传的临时文件获取音频时长
                    $tempFilePath = $file->getPathname();
                    if (file_exists($tempFilePath)) {
                        $duration = AudioHelper::getAudioDuration($tempFilePath);
                    }
                } catch (\Exception $e) {
                    // 获取时长失败时，记录日志但不影响上传
                    trace('获取音频时长失败: ' . $e->getMessage(), 'error');
                }
                
                // 创建音频记录
                $audioData = [
                    'room_id' => $roomId,
                    'folder_id' => $folderId ?: null,
                    'name' => $originalName,
                    'display_name' => $displayName,
                    'file_path' => $config['domain'] . '/' . $fileName,
                    'file_size' => $fileSize,
                    'duration' => $duration,
                    'format' => $extension,
                    'mime_type' => $config['mime_types'][$extension] ?? 'audio/mpeg',
                    'sort_order' => 0,
                    'status' => AudioModel::STATUS_NORMAL,
                    'create_time' => time() * 1000,
                    'update_time' => time() * 1000,
                ];

                $audioId = Db::name('api_audios')->insertGetId($audioData);
                
                if ($audioId) {
                    $uploadedFiles[] = array_merge($audioData, ['id' => $audioId]);
                    
                    // 更新文件夹音频数量统计
                    if ($folderId) {
                        $folder = FolderModel::find($folderId);
                        if ($folder) {
                            $folder->updateAudioCount();
                        }
                    }
                    
                    // 更新房间音频数量统计
                    $this->updateRoomAudioCount($roomId);
                }
            }

            if (empty($uploadedFiles)) {
                return $this->error('没有成功上传的文件');
            }

            return $this->success('上传成功', [
                'count' => count($uploadedFiles),
                'files' => $uploadedFiles
            ]);
        } catch (Exception $e) {
            return $this->error('上传失败: ' . $e->getMessage());
        }
    }

    /**
     * 上传音频文件（包含前端获取的时长信息）
     */
    public function uploadAudioWithInfo(): Response
    {
        $roomId = $this->request->post('room_id', 0);
        $folderId = $this->request->post('folder_id', null);
        $file = $this->request->file('file');
        
        // 从前端获取的音频信息
        $fileName = $this->request->post('file_name', '');
        $fileSize = $this->request->post('file_size', 0);
        $duration = (int)$this->request->post('duration', 0);
        $fileType = $this->request->post('file_type', '');
        
        if (empty($roomId)) {
            return $this->error('房间ID不能为空');
        }

        if (empty($file)) {
            return $this->error('请选择要上传的音频文件');
        }
        
        // 将空字符串转换为null
        if ($folderId === '' || $folderId === '0') {
            $folderId = null;
        }

        try {
            $config = $this->getQiniuConfig();
            $auth = new Auth($config['access_key'], $config['secret_key']);
            $uploadMgr = new UploadManager();

            // 验证文件类型
            $extension = strtolower($file->getOriginalExtension());
            if (!in_array($extension, $config['supported_formats'])) {
                return $this->error('不支持的音频格式');
            }

            // 验证文件大小
            if ($file->getSize() > $config['max_file_size']) {
                return $this->error('文件大小超过限制');
            }

            // 生成文件名
            $uploadFileName = 'audio/room' . $roomId . '/' . date('Ymd') . '/' . uniqid() . '.' . $extension;
            
            // 获取上传凭证
            $token = $auth->uploadToken($config['bucket']);
            
            // 上传到七牛云
            list($ret, $err) = $uploadMgr->putFile($token, $uploadFileName, $file->getPathname());
            
            if ($err !== null) {
                throw new \Exception('文件上传失败: ' . $err->message());
            }

            // 使用前端传来的信息，如果前端没有获取到时长，则尝试后端获取
            $finalDuration = $duration;
            if ($finalDuration <= 0) {
                try {
                    $tempFilePath = $file->getPathname();
                    if (file_exists($tempFilePath)) {
                        $finalDuration = AudioHelper::getAudioDuration($tempFilePath);
                    }
                } catch (\Exception $e) {
                    // 后端获取失败时使用默认值
                    $finalDuration = 0;
                }
            }
            
            // 处理文件名
            $originalName = $fileName ?: $file->getOriginalName();
            $displayName = pathinfo($originalName, PATHINFO_FILENAME);
            $actualFileSize = $fileSize ?: $file->getSize();
            
            // 创建音频记录
            $audioData = [
                'room_id' => $roomId,
                'folder_id' => $folderId ?: null,
                'name' => $originalName,
                'display_name' => $displayName,
                'file_path' => $config['domain'] . '/' . $uploadFileName,
                'file_size' => $actualFileSize,
                'duration' => $finalDuration,
                'format' => $extension,
                'mime_type' => $fileType ?: ($config['mime_types'][$extension] ?? 'audio/mpeg'),
                'sort_order' => 0,
                'status' => AudioModel::STATUS_NORMAL,
                'create_time' => time() * 1000,
                'update_time' => time() * 1000,
            ];

            $audioId = Db::name('api_audios')->insertGetId($audioData);
            
            if ($audioId) {
                // 更新文件夹音频数量统计
                if ($folderId) {
                    $folder = FolderModel::find($folderId);
                    if ($folder) {
                        $folder->updateAudioCount();
                    }
                }
                
                // 更新房间音频数量统计
                $this->updateRoomAudioCount($roomId);
                
                $result = array_merge($audioData, ['id' => $audioId]);
                
                return $this->success('上传成功', [
                    'audio' => $result,
                    'duration_source' => $duration > 0 ? 'frontend' : 'backend'
                ]);
            } else {
                return $this->error('保存音频信息失败');
            }
            
        } catch (Exception $e) {
            return $this->error('上传失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取文件夹列表
     */
    public function getFolders(): Response
    {
        $roomId = $this->request->get('room_id', 0);
        $parentId = $this->request->get('parent_id', null);
        
        // 将空字符串转换为null
        if ($parentId === '' || $parentId === '0') {
            $parentId = null;
        }

        if (empty($roomId)) {
            return $this->error('房间ID不能为空');
        }

        try {
            $folders = FolderModel::getChildFolders($roomId, $parentId);
            
            return $this->success('获取文件夹成功', $folders->toArray());
        } catch (Exception $e) {
            return $this->error('获取文件夹失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取房间内所有文件夹（用于移动文件时显示完整树形结构）
     */
    public function getAllFolders(): Response
    {
        $roomId = $this->request->get('room_id', 0);
        
        if (empty($roomId)) {
            return $this->error('房间ID不能为空');
        }

        try {
            // 获取房间内所有文件夹
            $folders = FolderModel::where('room_id', $roomId)
                ->order(['parent_id' => 'asc', 'sort_order' => 'asc', 'create_time' => 'asc'])
                ->select();

            $result = [];
            foreach ($folders as $folder) {
                $result[] = [
                    'id' => $folder->id,
                    'name' => $folder->name,
                    'parent_id' => $folder->parent_id,
                    'path' => $folder->path,
                    'audio_count' => $folder->audio_count,
                    'create_time' => $folder->create_time,
                    'update_time' => $folder->update_time
                ];
            }

            return $this->success('获取所有文件夹成功', $result);
        } catch (Exception $e) {
            return $this->error('获取文件夹失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取音频列表
     */
    public function getAudios(): Response
    {
        $roomId = $this->request->get('room_id', 0);
        $folderId = $this->request->get('folder_id', null);
        
        // 将空字符串转换为null
        if ($folderId === '' || $folderId === '0') {
            $folderId = null;
        }

        if (empty($roomId)) {
            return $this->error('房间ID不能为空');
        }

        try {
            $audios = AudioModel::getAudiosByFolder($roomId, $folderId);
            
            // 格式化返回数据
            $formattedAudios = [];
            foreach ($audios as $audio) {
                // 获取文件夹名称
                $folderName = '根目录';
                if ($audio->folder_id) {
                    $folder = FolderModel::find($audio->folder_id);
                    if ($folder) {
                        $folderName = $folder->name;
                    }
                }
                
                $formattedAudios[] = [
                    'id' => $audio->id,
                    'name' => $audio->name,
                    'display_name' => $audio->display_name,
                    'file_path' => $audio->file_path,
                    'file_size' => $audio->file_size,
                    'formatted_size' => $audio->getFormattedSize(),
                    'duration' => $audio->duration,
                    'formatted_duration' => $audio->getFormattedDuration(),
                    'format' => $audio->format,
                    'folder_id' => $audio->folder_id,
                    'folder_name' => $folderName,
                    'create_time' => $audio->create_time,
                    'update_time' => $audio->update_time,
                ];
            }
            
            return $this->success('获取音频列表成功', $formattedAudios);
        } catch (Exception $e) {
            return $this->error('获取音频列表失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取可选音频列表（用于音频选择弹窗）
     */
    public function getAvailableAudios(): Response
    {
        $roomId = $this->request->get('room_id', 0);
        $search = $this->request->get('search', '');
        $category = $this->request->get('category', '');
        $excludeIds = $this->request->get('exclude_ids', '');
        
        if (empty($roomId)) {
            return $this->error('房间ID不能为空');
        }

        try {
            // 构建查询
            $query = AudioModel::where('room_id', $roomId)
                ->where('status', AudioModel::STATUS_NORMAL);
            
            // 搜索筛选
            if (!empty($search)) {
                $query->where(function($q) use ($search) {
                    $q->whereLike('name', '%' . $search . '%')
                      ->whereOr('display_name', 'like', '%' . $search . '%');
                });
            }
            
            // 分类筛选
            if (!empty($category)) {
                if ($category === 'root') {
                    // 筛选根目录下的音频（folder_id 为 null 或 0）
                    $query->where(function($q) {
                        $q->whereNull('folder_id')->whereOr('folder_id', 0);
                    });
                } elseif (strpos($category, 'folder_') === 0) {
                    // 筛选指定文件夹下的音频
                    $folderId = str_replace('folder_', '', $category);
                    if (is_numeric($folderId)) {
                        $query->where('folder_id', $folderId);
                    }
                } else {
                    // 其他情况，可能是文件夹名称筛选
                    $folder = FolderModel::where('name', $category)->find();
                    if ($folder) {
                        $query->where('folder_id', $folder->id);
                    }
                }
            }
            
            // 排除已添加的音频ID
            if (!empty($excludeIds)) {
                $excludeArray = is_string($excludeIds) ? explode(',', $excludeIds) : $excludeIds;
                if (!empty($excludeArray)) {
                    $query->whereNotIn('id', $excludeArray);
                }
            }
            
            $audios = $query->order(['create_time' => 'desc'])->select();
            
            // 格式化返回数据
            $formattedAudios = [];
            foreach ($audios as $audio) {
                // 获取文件夹名称作为分类
                $categoryName = '未分类';
                if ($audio->folder_id) {
                    $folder = FolderModel::find($audio->folder_id);
                    if ($folder) {
                        $categoryName = $folder->name;
                    }
                }
                
                $formattedAudios[] = [
                    'id' => $audio->id,
                    'name' => $audio->display_name ?: $audio->name,
                    'file_name' => $audio->name,
                    'category' => $categoryName,
                    'duration' => $audio->duration,
                    'file_path' => $audio->file_path,
                    'file_size' => $audio->file_size,
                    'formatted_size' => $audio->getFormattedSize(),
                    'formatted_duration' => $audio->getFormattedDuration(),
                    'format' => $audio->format,
                    'folder_id' => $audio->folder_id,
                    'create_time' => $audio->create_time,
                ];
            }
            
            return $this->success('获取可选音频列表成功', $formattedAudios);
        } catch (Exception $e) {
            return $this->error('获取可选音频列表失败: ' . $e->getMessage());
        }
    }

    /**
     * 创建文件夹
     */
    public function createFolder(): Response
    {
        $roomId = $this->request->post('room_id', 0);
        $parentId = $this->request->post('parent_id', null);
        $name = $this->request->post('name', '');

        if (empty($roomId)) {
            return $this->error('房间ID不能为空');
        }

        if (empty($name)) {
            return $this->error('文件夹名称不能为空');
        }

        try {
            // 构建路径
            $parentPath = '';
            $level = 1;
            
            if ($parentId) {
                $parentFolder = FolderModel::find($parentId);
                if (!$parentFolder) {
                    return $this->error('父文件夹不存在');
                }
                $parentPath = $parentFolder->path;
                $level = $parentFolder->level + 1;
            }
            
            $path = FolderModel::buildPath($parentPath, $name);
            
            // 检查同级文件夹名称是否重复
            $exists = FolderModel::where('room_id', $roomId)
                ->where('parent_id', $parentId)
                ->where('name', $name)
                ->find();
                
            if ($exists) {
                return $this->error('同级文件夹中已存在相同名称');
            }

            $folderData = [
                'room_id' => $roomId,
                'parent_id' => $parentId,
                'name' => $name,
                'path' => $path,
                'level' => $level,
                'sort_order' => 0,
                'audio_count' => 0,
                'create_time' => time() * 1000,
                'update_time' => time() * 1000,
            ];

            $folderId = Db::name('api_folders')->insertGetId($folderData);

            if ($folderId) {
                return $this->success('创建文件夹成功', array_merge($folderData, ['id' => $folderId]));
            } else {
                return $this->error('创建文件夹失败');
            }
        } catch (Exception $e) {
            return $this->error('创建文件夹失败: ' . $e->getMessage());
        }
    }

    /**
     * 重命名文件夹
     */
    public function updateFolder(): Response
    {
        $folderId = $this->request->post('folder_id', 0);
        $name = $this->request->post('name', '');

        if (empty($folderId)) {
            return $this->error('文件夹ID不能为空');
        }

        if (empty($name)) {
            return $this->error('文件夹名称不能为空');
        }

        try {
            $folder = FolderModel::find($folderId);
            if (!$folder) {
                return $this->error('文件夹不存在');
            }

            // 检查同级文件夹名称是否重复
            $exists = FolderModel::where('room_id', $folder->room_id)
                ->where('parent_id', $folder->parent_id)
                ->where('name', $name)
                ->where('id', '<>', $folderId)
                ->find();
                
            if ($exists) {
                return $this->error('同级文件夹中已存在相同名称');
            }

            // 构建新路径
            $parentPath = '';
            if ($folder->parent_id) {
                $parentFolder = FolderModel::find($folder->parent_id);
                if ($parentFolder) {
                    $parentPath = $parentFolder->path;
                }
            }
            
            $newPath = FolderModel::buildPath($parentPath, $name);

            $result = $folder->save([
                'name' => $name,
                'path' => $newPath,
                'update_time' => time() * 1000
            ]);

            if ($result) {
                // TODO: 如果有子文件夹，需要更新子文件夹的路径
                return $this->success('重命名成功');
            } else {
                return $this->error('重命名失败');
            }
        } catch (Exception $e) {
            return $this->error('重命名失败: ' . $e->getMessage());
        }
    }

    /**
     * 删除文件夹
     */
    public function deleteFolder(): Response
    {
        $folderId = $this->request->post('folder_id', 0);

        if (empty($folderId)) {
            return $this->error('文件夹ID不能为空');
        }

        try {
            $folder = FolderModel::find($folderId);
            if (!$folder) {
                return $this->error('文件夹不存在');
            }

            // 检查是否有子文件夹
            $hasChildren = FolderModel::where('parent_id', $folderId)->count();
            if ($hasChildren > 0) {
                return $this->error('请先删除子文件夹');
            }

            // 检查是否有音频文件
            $hasAudios = AudioModel::where('folder_id', $folderId)
                ->where('status', AudioModel::STATUS_NORMAL)
                ->count();
            if ($hasAudios > 0) {
                return $this->error('请先删除或移动文件夹中的音频文件');
            }

            $result = $folder->delete();

            if ($result) {
                return $this->success('删除文件夹成功');
            } else {
                return $this->error('删除文件夹失败');
            }
        } catch (Exception $e) {
            return $this->error('删除文件夹失败: ' . $e->getMessage());
        }
    }

    /**
     * 移动音频文件
     */
    public function moveAudio(): Response
    {
        $audioId = $this->request->post('audio_id', 0);
        $targetFolderId = $this->request->post('target_folder_id', null);

        if (empty($audioId)) {
            return $this->error('音频ID不能为空');
        }

        try {
            $audio = AudioModel::find($audioId);
            if (!$audio) {
                return $this->error('音频文件不存在');
            }

            $result = $audio->moveToFolder($targetFolderId);

            if ($result) {
                return $this->success('移动成功');
            } else {
                return $this->error('移动失败');
            }
        } catch (Exception $e) {
            return $this->error('移动失败: ' . $e->getMessage());
        }
    }

    /**
     * 重命名音频文件
     */
    public function renameAudio(): Response
    {
        $audioId = $this->request->post('audio_id', 0);
        $displayName = $this->request->post('display_name', '');

        if (empty($audioId)) {
            return $this->error('音频ID不能为空');
        }

        if (empty($displayName)) {
            return $this->error('音频名称不能为空');
        }

        try {
            $audio = AudioModel::find($audioId);
            if (!$audio) {
                return $this->error('音频文件不存在');
            }

            // 构建新的文件名（保留扩展名）
            $extension = pathinfo($audio->name, PATHINFO_EXTENSION);
            $newName = $displayName . '.' . $extension;

            $result = $audio->rename($newName, $displayName);

            if ($result) {
                return $this->success('重命名成功');
            } else {
                return $this->error('重命名失败');
            }
        } catch (Exception $e) {
            return $this->error('重命名失败: ' . $e->getMessage());
        }
    }

    /**
     * 删除音频文件
     */
    public function deleteAudio(): Response
    {
        $audioId = $this->request->post('audio_id', 0);

        if (empty($audioId)) {
            return $this->error('音频ID不能为空');
        }

        try {
            $audio = AudioModel::find($audioId);
            if (!$audio) {
                return $this->error('音频文件不存在');
            }

            $roomId = $audio->room_id;
            
            // 软删除音频文件
            $result = $audio->softDelete();

            if ($result) {
                // 更新房间音频数量统计
                $this->updateRoomAudioCount($roomId);
                
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (Exception $e) {
            return $this->error('删除失败: ' . $e->getMessage());
        }
    }

    /**
     * 批量删除音频文件（软删除）
     */
    public function batchDeleteAudios(): Response
    {
        $audioIds = $this->request->post('audio_ids', []);

        if (empty($audioIds) || !is_array($audioIds)) {
            return $this->error('音频ID列表不能为空');
        }

        try {
            $successCount = 0;
            $failedCount = 0;
            $roomIds = [];
            $folderIds = [];

            foreach ($audioIds as $audioId) {
                $audio = AudioModel::find($audioId);
                if ($audio) {
                    $roomIds[] = $audio->room_id;
                    if ($audio->folder_id) {
                        $folderIds[] = $audio->folder_id;
                    }
                    $result = $audio->softDelete(false); // 批量删除时不立即更新文件夹统计
                    if ($result) {
                        $successCount++;
                    } else {
                        $failedCount++;
                    }
                } else {
                    $failedCount++;
                }
            }

            // 更新受影响的文件夹音频数量统计（避免重复更新）
            $folderIds = array_unique($folderIds);
            foreach ($folderIds as $folderId) {
                $folder = FolderModel::find($folderId);
                if ($folder) {
                    $folder->updateAudioCount();
                }
            }

            // 更新房间音频数量统计
            $roomIds = array_unique($roomIds);
            foreach ($roomIds as $roomId) {
                $this->updateRoomAudioCount($roomId);
            }

            if ($failedCount === 0) {
                return $this->success("成功删除 {$successCount} 个音频文件");
            } else {
                return $this->success("删除完成：成功 {$successCount} 个，失败 {$failedCount} 个");
            }
        } catch (Exception $e) {
            return $this->error('批量删除失败: ' . $e->getMessage());
        }
    }

    /**
     * 真实删除音频文件（永久删除数据库记录和七牛云文件）
     */
    public function realDeleteAudios(): Response
    {
        $audioIds = $this->request->post('audio_ids', []);

        if (empty($audioIds) || !is_array($audioIds)) {
            return $this->error('音频ID列表不能为空');
        }

        try {
            $successCount = 0;
            $failedCount = 0;
            $qiniuSuccessCount = 0;
            $qiniuFailedCount = 0;
            $roomIds = [];
            $folderIds = [];
            $deleteResults = [];

            foreach ($audioIds as $audioId) {
                $audio = AudioModel::find($audioId);
                if ($audio) {
                    $roomIds[] = $audio->room_id;
                    // 记录文件夹ID（需要在删除前记录）
                    if ($audio->folder_id) {
                        $folderIds[] = $audio->folder_id;
                    }
                    
                    // 删除七牛云文件
                    $qiniuDeleted = $this->deleteQiniuFile($audio->file_path);
                    
                    if ($qiniuDeleted) {
                        $qiniuSuccessCount++;
                    } else {
                        $qiniuFailedCount++;
                    }
                    
                    // 无论七牛云删除是否成功，都删除数据库记录
                    // 因为可能是文件已经不存在或配置问题
                    $result = $audio->delete();
                    if ($result) {
                        $successCount++;
                        $deleteResults[] = [
                            'name' => $audio->name,
                            'database' => true,
                            'qiniu' => $qiniuDeleted
                        ];
                    } else {
                        $failedCount++;
                        $deleteResults[] = [
                            'name' => $audio->name,
                            'database' => false,
                            'qiniu' => $qiniuDeleted
                        ];
                    }
                } else {
                    $failedCount++;
                    $deleteResults[] = [
                        'name' => "ID: {$audioId}",
                        'database' => false,
                        'qiniu' => false,
                        'error' => '音频记录不存在'
                    ];
                }
            }

            // 更新受影响的文件夹音频数量统计
            $folderIds = array_unique($folderIds);
            foreach ($folderIds as $folderId) {
                $folder = FolderModel::find($folderId);
                if ($folder) {
                    $folder->updateAudioCount();
                }
            }

            // 更新房间音频数量统计
            $roomIds = array_unique($roomIds);
            foreach ($roomIds as $roomId) {
                $this->updateRoomAudioCount($roomId);
            }

            // 构造详细的返回信息
            $message = "删除操作完成！\n";
            $message .= "数据库删除：成功 {$successCount} 个，失败 {$failedCount} 个\n";
            $message .= "七牛云删除：成功 {$qiniuSuccessCount} 个，失败 {$qiniuFailedCount} 个";

            return $this->success($message, [
                'database_success' => $successCount,
                'database_failed' => $failedCount,
                'qiniu_success' => $qiniuSuccessCount,
                'qiniu_failed' => $qiniuFailedCount,
                'details' => $deleteResults
            ]);
        } catch (Exception $e) {
            return $this->error('真实删除失败: ' . $e->getMessage());
        }
    }

    /**
     * 删除七牛云文件
     */
    private function deleteQiniuFile($filePath): bool
    {
        try {
            // 获取七牛云配置
            $config = $this->getQiniuConfig();
            
            if (empty($config) || !isset($config['access_key']) || !isset($config['secret_key']) || !isset($config['bucket'])) {
                trace('七牛云配置不完整，跳过云端文件删除', 'warning');
                return true; // 配置不完整时跳过云端删除，但不影响数据库删除
            }
            
            // 创建七牛云认证对象
            $auth = new Auth($config['access_key'], $config['secret_key']);
            $bucketMgr = new BucketManager($auth);
            
            // 从完整URL中提取文件key
            $key = $this->extractKeyFromPath($filePath, $config);
            
            if (empty($key)) {
                trace('无法从路径中提取有效的文件key: ' . $filePath, 'warning');
                return false;
            }
            
            // 删除七牛云文件
            $err = $bucketMgr->delete($config['bucket'], $key);
            
            if ($err === null) {
                trace('成功删除七牛云文件: ' . $key, 'info');
                return true;
            } else {
                trace('七牛云文件删除失败: ' . json_encode($err), 'error');
                return false;
            }
            
        } catch (Exception $e) {
            // 记录错误日志
            trace('七牛云文件删除异常: ' . $e->getMessage(), 'error');
            return false;
        }
    }

    /**
     * 从文件路径中提取七牛云存储的key
     */
    private function extractKeyFromPath($filePath, $config): string
    {
        try {
            // 如果是完整URL，需要提取文件名部分
            if (strpos($filePath, 'http') === 0) {
                // 去除域名部分，获取文件key
                if (isset($config['domain'])) {
                    $domain = rtrim($config['domain'], '/');
                    $filePath = str_replace($domain . '/', '', $filePath);
                    $filePath = str_replace($domain, '', $filePath);
                }
                
                // 去除协议和可能的域名，获取纯文件路径
                $urlParts = parse_url($filePath);
                if (isset($urlParts['path'])) {
                    $filePath = ltrim($urlParts['path'], '/');
                } else {
                    // 如果解析失败，直接取URL的文件名部分
                    $filePath = basename($filePath);
                }
            }
            
            // 移除可能的前导斜杠
            $key = ltrim($filePath, '/');
            
            // 验证key是否有效（不为空且不是根路径）
            if (empty($key) || $key === '/') {
                return '';
            }
            
            return $key;
            
        } catch (Exception $e) {
            trace('提取文件key失败: ' . $e->getMessage(), 'error');
            return '';
        }
    }

    /**
     * 真实删除单个音频文件（用于进度显示）
     */
    public function realDeleteSingleAudio(): Response
    {
        $audioId = $this->request->post('audio_id', 0);

        if (empty($audioId)) {
            return $this->error('音频ID不能为空');
        }

        try {
            $audio = AudioModel::find($audioId);
            if (!$audio) {
                return $this->error('音频文件不存在');
            }

            $roomId = $audio->room_id;
            $folderId = $audio->folder_id;
            
            // 删除七牛云文件
            $qiniuDeleted = $this->deleteQiniuFile($audio->file_path);
            $qiniuError = null;
            if (!$qiniuDeleted) {
                $qiniuError = '七牛云文件删除失败';
            }
            
            // 删除数据库记录
            $databaseDeleted = $audio->delete();
            $databaseError = null;
            if (!$databaseDeleted) {
                $databaseError = '数据库记录删除失败';
            }

            // 更新文件夹音频数量统计
            if ($databaseDeleted && $folderId) {
                $folder = FolderModel::find($folderId);
                if ($folder) {
                    $folder->updateAudioCount();
                }
            }

            // 更新房间音频数量统计
            if ($databaseDeleted) {
                $this->updateRoomAudioCount($roomId);
            }

            return $this->success('删除完成', [
                'database_success' => $databaseDeleted,
                'qiniu_success' => $qiniuDeleted,
                'database_error' => $databaseError,
                'qiniu_error' => $qiniuError
            ]);

        } catch (Exception $e) {
            return $this->error('删除失败: ' . $e->getMessage());
        }
    }

    /**
     * 测试七牛云连接配置
     */
    public function testQiniuConnection(): Response
    {
        try {
            $config = $this->getQiniuConfig();
            
            if (empty($config)) {
                return $this->error('七牛云配置未找到');
            }
            
            $requiredKeys = ['access_key', 'secret_key', 'bucket', 'domain'];
            $missingKeys = [];
            
            foreach ($requiredKeys as $key) {
                if (!isset($config[$key]) || empty($config[$key])) {
                    $missingKeys[] = $key;
                }
            }
            
            if (!empty($missingKeys)) {
                return $this->error('七牛云配置不完整，缺少: ' . implode(', ', $missingKeys));
            }
            
            // 尝试创建BucketManager
            $auth = new Auth($config['access_key'], $config['secret_key']);
            $bucketMgr = new BucketManager($auth);
            
            // 尝试获取存储空间信息（这不会产生费用）
            $buckets = $bucketMgr->buckets();
            
            if (isset($buckets[0]) && is_array($buckets[0])) {
                $availableBuckets = $buckets[0];
                if (in_array($config['bucket'], $availableBuckets)) {
                    return $this->success('七牛云连接测试成功', [
                        'bucket' => $config['bucket'],
                        'domain' => $config['domain'],
                        'available_buckets' => $availableBuckets
                    ]);
                } else {
                    return $this->error('指定的存储空间不存在: ' . $config['bucket']);
                }
            } else {
                return $this->error('无法获取存储空间列表，请检查AccessKey和SecretKey');
            }
            
        } catch (Exception $e) {
            return $this->error('七牛云连接测试失败: ' . $e->getMessage());
        }
    }

    /**
     * 刷新文件夹音频统计（修复数据不一致问题）
     */
    public function refreshFolderStats(): Response
    {
        $roomId = $this->request->post('room_id', 0);
        
        if (empty($roomId)) {
            return $this->error('房间ID不能为空');
        }

        try {
            // 获取房间内所有文件夹
            $folders = FolderModel::where('room_id', $roomId)->select();
            
            $updatedCount = 0;
            foreach ($folders as $folder) {
                $folder->updateAudioCount();
                $updatedCount++;
            }
            
            // 更新房间音频数量统计
            $this->updateRoomAudioCount($roomId);
            
            return $this->success("成功刷新 {$updatedCount} 个文件夹的音频统计");
        } catch (Exception $e) {
            return $this->error('刷新统计失败: ' . $e->getMessage());
        }
    }

    /**
     * 更新房间音频数量统计
     */
    private function updateRoomAudioCount($roomId)
    {
        try {
            $count = AudioModel::where('room_id', $roomId)
                ->where('status', AudioModel::STATUS_NORMAL)
                ->count();
                
            Db::name('api_rooms')->where('id', $roomId)->update([
                'audio_count' => $count,
                'update_time' => time() * 1000
            ]);
        } catch (Exception $e) {
            // 静默处理统计更新失败
        }
    }

}
